<?php

namespace app\xinrong\controller;

use app\xinrong\model\XinrongCostModel;
use app\xinrong\model\XinrongCostTypeModel;
use app\xinrong\model\XinrongMaterialModel;
use app\xinrong\model\XinrongProduceModel;
use app\xinrong\model\XinrongProductModel;
use cmf\controller\AdminBaseController;

class ProduceController extends AdminBaseController
{
    public function index()
    {
        $where = [
            'status' => 1
        ];
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['name'] = ['like', "%$keyword%"];
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['name|area'] = ['like', "%$keyword%"];
        }
        $xinrongProduceModel = new XinrongProduceModel();
        $lists = $xinrongProduceModel
            ->where($where)
            ->order('id desc')
            ->paginate();

        $lists->appends(input());

        $this->assign('lists', $lists);
        $this->assign('page', $lists->render());
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $arrData = $this->request->post();
            $arrData['manager'] = cmf_get_current_admin_id();


            $xinrongMaterialModel = new XinrongMaterialModel();
            if (isset($arrData['mid']) && $arrData['mid']) {
                $arrData['material'] = $xinrongMaterialModel
                    ->where([
                        'id' => ['in', $arrData['mid']]
                    ])
                    ->sum('cost');
            }
            $xinrongProduceModel = new XinrongProduceModel();
            $xinrongProduceModel->allowField(true)->save($arrData);
            if ($arrData === false) {
                $this->error($xinrongProduceModel->getError());
            }

            if (isset($arrData['mid']) && $arrData['mid']) {
                $xinrongMaterialModel
                    ->save([
                        'to_id' => $xinrongProduceModel->id,
                        'status' => 2,
                        'to_type' => 1
                    ], [
                        'id' => ['in', $arrData['mid']],
                        'status' => 1
                    ]);
            }

            if (isset($arrData['cost'][3])) {
                $id = $xinrongProduceModel->id;
                $costs = [];
                $cost = 0;
                foreach ($arrData['cost'][3] as $key => $val) {
                    $costs[] = [
                        'cost' => $val,
                        'cid' => $key,
                        'tid' => 3,
                        'pid' => $id,
                    ];
                    $cost += $val;
                }
                if ($costs) {
                    $xinrongCostModel = new XinrongCostModel();
                    $xinrongCostModel->saveAll($costs);
                    $xinrongProduceModel->where([
                        'id' => $id
                    ])->setField('accessory_material', $cost);
                }
            }
            $this->success('添加成功！', url('index'));
        }
        $xinrongCostTypeModel = new XinrongCostTypeModel();
        $types = $xinrongCostTypeModel
            ->where([
                'cid' => 3
            ])
            ->select();

        $this->assign('types', $types);
        return $this->fetch();
    }

    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            $this->error('访问错误');
        }
        $xinrongProduceModel = new XinrongProduceModel();
        $result = $xinrongProduceModel
            ->alias('produce')
            ->join('__XINRONG_MATERIAL__ material','produce.id = material.to_id and material.to_type=1 and material.status = 2','left')
            ->group('produce.id')
            ->field('produce.*,group_concat(material.name) material_name,group_concat(material.id) material_ids')
            ->with(['costs' => function ($query) {
                $query->where([
                    'tid' => 3
                ]);
            }])->find($id);

        if ($this->request->isPost()) {
            $arrData = $this->request->post();

            $xinrongMaterialModel = new XinrongMaterialModel();
            if (isset($arrData['mid']) && $arrData['mid']) {
                $xinrongMaterialModel
                    ->save([
                        'to_id' => 0,
                        'status' => 1,
                        'to_type' => 0
                    ], [
                        'to_type' => 1,
                        'to_id' => $id,
                        'status' => 2
                    ]);
                $xinrongMaterialModel
                    ->save([
                        'to_id' => $id,
                        'status' => 2,
                        'to_type' => 1
                    ], [
                        'id' => ['in', $arrData['mid']],
                        'status' => 1
                    ]);
                $arrData['material'] = $xinrongMaterialModel
                    ->where([
                        'id' => ['in', $arrData['mid']]
                    ])
                    ->sum('cost');
            }else{
                $xinrongMaterialModel
                    ->save([
                        'to_id' => 0,
                        'status' => 1,
                        'to_type' => 0
                    ], [
                        'to_type' => 1,
                        'to_id' => $id,
                        'status' => 2
                    ]);
                $arrData['material'] = 0;
            }

            $xinrongProduceModel = new XinrongProduceModel();
            $xinrongProduceModel->allowField(true)->save($arrData, ['id' => $id]);
            if (isset($arrData['cost'][3])) {
                $cost = 0;
                $xinrongCostModel = new XinrongCostModel();
                foreach ($arrData['cost'][3] as $key => $val) {
                    $flag = true;
                    foreach ($result['costs'] as $costs) {
                        if ($costs['cid'] == $key) {
                            if ($costs['cost'] != $val) {
                                $xinrongCostModel->where([
                                    'id' => $costs['id']
                                ])->setField('cost', $val);
                            }
                            $flag = false;
                            break;
                        }
                    }
                    if ($flag) {
                        $xinrongCostModel->save([
                            'cost' => $val,
                            'cid' => $key,
                            'tid' => 3,
                            'pid' => $id,
                        ]);
                    }
                    $cost += $val;
                }
                if ($cost != $result['accessory_material']) {
                    $xinrongProduceModel->where([
                        'id' => $id
                    ])->setField('accessory_material', $cost);
                }
            }
            $this->success('保存成功！', url('index'));
        }

        $xinrongCostTypeModel = new XinrongCostTypeModel();
        $types = $xinrongCostTypeModel
            ->where([
                'cid' => 3
            ])
            ->select();

        foreach ($types as $type) {
            $type->setAttr('cost', 0);
            foreach ($result['costs'] as $cost) {
                if ($cost['cid'] == $type['id']) {
                    $type->setAttr('cost', $cost['cost']);
                    break;
                }
            }
        }

        $this->assign('types', $types);
        $this->assign('result', $result);
        return $this->fetch();
    }

    public function conversion()
    {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->error('访问错误！');
        }
        $xinrongProduceModel = new XinrongProduceModel();
        $result = $xinrongProduceModel->find($id);
        if(!$result) {
            $this->error('访问错误！');
        }
        if($this->request->isPost()) {
            $price = $this->request->post('price');

            $xinrongProductModel = new XinrongProductModel();
            $flag = $xinrongProductModel->save([
                'name' => $result['name'],
                'reg_time' => $result['reg_time'],
                'cost' => $result['material'] + $result['accessory_material'] + $result['manpower'] + $result['apportion'],
                'manager' => cmf_get_current_admin_id(),
                'type' => $result['reg_type'],
                'status' => 1,
                'price' => $price,
                'area' => $result['area'],
                'end_time' => $result['end_time'],
                'registered_capital' => $result['registered_capital'],
                'corporation' => $result['corporation'],
                'score' => 1,
            ]);
            if($flag === false) {
                $this->error('转化失败！');
            }


            $xinrongProduceModel->save([
                'status' => 2,
                'to_id' => $xinrongProductModel->id,
                'to_type' => 1
            ],[
                'id' => $id,
                'status' => 1
            ]);
            $this->success('转化成功！',url('product/index'));
        }

        $this->assign('result',$result);
        return $this->fetch();
    }

    public function restore() {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->error('访问错误！');
        }
        $xinrongProduceModel = new XinrongProduceModel();
        $info = $xinrongProduceModel->save([
            'status' => 0
        ],[
            'id' => $id
        ]);

        $xinrongMaterialModel = new XinrongMaterialModel();
        $xinrongMaterialModel->save([
            'status' => 1
        ],[
            'status' => 2,
            'to_id' => $id,
            'to_type' => 1
        ]);
        $this->success('还原成功！');
    }
}